<template>
  <view class="page">
    <view class="seachPart flex align-center justify-between">
      <view class="flex align-center" v-if="loginStatus">
        <image
          @click="goToInfo"
          class="seachImg"
          :src="
            doorPhoto
              ? doorPhoto
              : 'https://app-cangshu.oss-rg-china-mainland.aliyuncs.com/asssets/cashRegisterImg/chuanShu.png'
          "
          mode="scaleToFill"
        />
        <view class="filter">
          <picker @change="handlePickerChange" :range="options">
            <view class="flex align-center">
              <view class="title col-balck f-s-32 fw-600">{{
                selectedOption
              }}</view>
              <image
                src="https://app-cangshu.oss-rg-china-mainland.aliyuncs.com/asssets/merchant/downPoint.png"
                class="downPoint"
                mode="scaleToFill"
              />
            </view>
            <view class="code dinAlternate f-s-30 fw-600">{{
              selectedCode
            }}</view>
          </picker>
        </view>
      </view>
      <view class="f-s-36" v-else @click="power">请登录</view>
    </view>
    <view class="businessTotal borderRadius23" @click="goToFinance">
      <view class="businessTitle fw-600 f-s-32 col-white">总营业额</view>
      <view class="flex justify-between align-end">
        <view class="fraction"
          ><text class="dinAlternate col-white">{{ allSales }}</text
          ><text class="unit f-s-28 fw-400 col-white">元</text></view
        >
        <view class="details flex col-white align-center">
          <view>收益详情</view>
          <image
            src="https://app-cangshu.oss-rg-china-mainland.aliyuncs.com/asssets/merchant/arrowRightArrow.png"
            class="forwardArrow"
            mode="scaleToFill"
          />
        </view>
      </view>
    </view>
    <view class="flex justify-between mt-17">
      <cardModule
        class="cardPart"
        :mark="1"
        v-for="(item, index) in totalList"
        :dataObject="item"
        :key="index"
      ></cardModule>
    </view>
    <view
      class="scanPart borderRadius23 bg-white flex align-center justify-center"
      @click="goToReceivePay"
    >
      <image
        class="merchanTreceivePay"
        src="https://app-cangshu.oss-rg-china-mainland.aliyuncs.com/asssets/merchant/merchantCollection.png"
        mode="scaleToFill"
      />
      <view class="scanPartTitle fw-600 f-s-28 ml20">获取收款码</view>
    </view>
    <view class="todayStore borderRadius23 bg-white">
      <view class="headStore borderRadius23 bg-f6f6f6">
        <view class="flex align-end">
          <view class="todayTitle fw-600 f-s-28 col-black">今日店铺积分</view>
          <view class="todayDate fw-600">
            截止到<text>{{ todayTime }}</text>
          </view>
        </view>
        <view class="flex mt-24">
          <view
            v-for="(item, index) in numList"
            :key="index"
            class="flex align-end"
          >
            <view
              class="numPart flex align-center justify-center"
              :class="index !== 0 ? 'ml9' : ''"
            >
              <view class="numMark fw-600 col-balck dinAlternate">{{
                item
              }}</view>
            </view>
            <view class="drop" v-if="index == 6"></view>
          </view>
        </view>
      </view>
      <view class="flex justify-between mt-17">
        <cardModule
          class="cardPart"
          :mark="2"
          v-for="(item, index) in totalProfit"
          :dataObject="item"
          :key="index"
        ></cardModule>
      </view>
      <view class="flex mt-17 align-center">
        <view class="iconXinghao">*</view>
        <view class="introduce">统计数据时间：<text>今日0:00～当前</text></view>
      </view>
    </view>
    <view
      @click="yesterShow = !yesterShow"
      v-if="!yesterShow"
      class="yesterday mt-17 flex flex-column justify-center align-center borderRadius23 bg-white"
    >
      <image
        src="https://app-cangshu.oss-rg-china-mainland.aliyuncs.com/asssets/merchant/downPoint.png"
        class="downPoint"
        mode="scaleToFill"
      />
      <view class="f-s-28 mt15 fw-600">展开昨日数据</view>
    </view>
    <view class="detailedPart mt-17 borderRadius23 bg-white" v-if="yesterShow">
      <view class="header f-s-28 fw-600 col-black">昨日数据</view>
      <view class="flex justify-between mt-17">
        <cardModule
          class="cardPart"
          :mark="2"
          v-for="(e, id) in yesterList"
          :dataObject="e"
          :key="id"
        ></cardModule>
      </view>
    </view>
    <view
      @click="yesterShow = !yesterShow"
      v-if="yesterShow"
      class="yesterday mt-17 flex flex-column justify-center align-center borderRadius23 bg-white"
    >
      <image
        src="https://app-cangshu.oss-rg-china-mainland.aliyuncs.com/asssets/merchant/upwardPoint.png"
        class="downPoint"
        mode="scaleToFill"
      />
      <view class="f-s-28 mt15 fw-600">收起昨日数据</view>
    </view>
    <view
      class="detailedPart mt-17 borderRadius23 bg-white"
      v-for="(item, index) in detailedList"
      @click="goToInformation(item)"
      :key="index"
    >
      <view class="header f-s-28 fw-600 col-black">{{ item.title }}</view>
      <view class="flex justify-between mt-17">
        <cardModule
          class="cardPart"
          :mark="2"
          v-for="(e, id) in item.list"
          :dataObject="e"
          :key="id"
        ></cardModule>
      </view>
    </view>
    <!-- <view class="tradePart bg-white">
      <dataStatistics
        :merchantId="merchantId"
        :loginStatus="loginStatus"
      ></dataStatistics>
    </view> -->
    <view style="padding-bottom: 110px">
      <!-- 确保内容不被 TabBar 遮挡 -->
    </view>
    <custom-tabbar :selected="0" @change="onTabChange" />
    <!-- <customTabBar ref="customTabBar"></customTabBar> -->
  </view>
</template>
<script>
// import { dataStatistics } from "./components/dataStatistics.vue";
import customTabbar from "@/components/custom-tabbar.vue";
import cardModule from "./components/cardModule.vue";
import { mapGetters } from "vuex";
import {
  getUserInfoData,
  getTenantBySelf,
  getMerchantRecords,
} from "@/api/user.js";
import Cache from "@/utils/cache";
import { LOGIN_STATUS } from "@/config/cache";
export default {
  components: {
    // dataStatistics,
    customTabbar,
    cardModule,
  },
  computed: mapGetters(["isLogin"]),
  data() {
    return {
      options: [],
      codeOptions: [],
      selectedOption: "暂无商家",
      searchvalue: 0,
      selectedCode: "",
      yesterShow: false, // 是否显示昨日数据true为展开、false为收起
      numList: [0, 0, 0, 0, 0, 0, 0, 0, 0],
      allSales: 0, // 总营业额
      totalList: [
        { name: "积分总量", key: "allPoints", value: 0 },
        { name: "订单总量", key: "allOrderNum", value: 0 },
        { name: "抵用券总量", key: "allVoucher", value: 0 },
      ],
      // 今日业额
      totalProfit: [
        { name: "今日营业额", key: "todaySales", value: 0 },
        { name: "订单量(单)", key: "todayOrderNum", value: 0 },
        { name: "应收金额", key: "todayPayMoney", value: 0 },
      ],
      // 昨日数据
      yesterList: [
        { name: "营业额", key: "yesterdaySales", value: 0 },
        { name: "订单量(单)", key: "yesterdayOrderNum", value: 0 },
        { name: "应收金额", key: "yesterdayPayMoney", value: 0 },
      ],
      // 抵用卷和积分明细
      detailedList: [
        {
          title: "抵用券明细",
          mark: "1",
          list: [
            { name: "可用抵用券", key: "todayOkVoucher", value: 0 },
            { name: "冻结抵用券", key: "todayFreezeVoucher", value: 0 },
            { name: "奖励抵用券", key: "todayRewardVoucher", value: 0 },
          ],
        },
        {
          title: "积分明细",
          mark: "2",
          list: [
            { name: "补贴积分", key: "todayPerkPoints", value: 0 },
            { name: "用户积分", key: "todayUserPoints", value: 0 },
            { name: "奖励积分", key: "todayRewardPoints", value: 0 },
          ],
        },
      ],
      loginStatus: false,
      doorPhoto: "", // 门头照片
      merchantId: "", // 商户ID
      imgList: [
        {
          img: "https://app-cangshu.oss-rg-china-mainland.aliyuncs.com/asssets/merchant/merchantRotation.png",
          active: true,
        },
      ],
      userInfo: {},
      todayTime: "", // 今日日期
    };
  },
  mounted() {
    this.getUserInfo();
    this.todayTime = this.getFormattedDate();
  },
  onShow() {
    // 获取自定义 tabBar 实例并更新选中项
    // this._data.currentIndex = 0;
    // if (typeof this.getTabBar === "function" && this.getTabBar()) {
    //   this.getTabBar().setData({
    //     currentIndex: 0, // 首页对应 list 的索引
    //   });
    // }
  },
  methods: {
    // 今日日期
    getFormattedDate() {
      const today = new Date();
      const year = today.getFullYear();
      const month = String(today.getMonth() + 1).padStart(2, "0");
      const day = String(today.getDate()).padStart(2, "0");
      return `${year}年${month}月${day}日`;
    },
    // 前往积分和抵用券信息页面
    goToInformation(data) {
      uni.navigateTo({
        url: "/pages/information/index?mark=" + data.mark,
      });
    },
    // 前往财务数据页面
    goToFinance() {
      uni.navigateTo({
        url: "/pages/finance/index",
      });
    },
    // 前往商家海报
    goToReceivePay() {
      if (this.loginStatus) {
        uni.navigateTo({
          url: "/pages/merchanTreceivePay/index?merchantId=" + this.merchantId,
        });
      } else {
        uni.navigateTo({
          url: `/pages/login/index`,
        });
      }
    },
    getTenantBySelfData() {
      getTenantBySelf().then((res) => {
        this.options = [];
        this.codeOptions = [];
        res.data.forEach((item) => {
          let str = {
            value: item.shortName || item.name,
            code: item.code,
            id: item.id,
          };
          this.codeOptions.push(str);
          if (item.shortName) {
            this.options.push(item.shortName);
          } else {
            this.options.push(item.name);
          }
        });
        this.merchantId = res.data[0].id;
        this.selectedOption = res.data[0].shortName || res.data[0].name;
        this.selectedCode = res.data[0].code;
        this.doorPhoto = res.data[0].storeHeaderPicLocal;
        this.getMerchantRecordsData();
      });
    },
    // 新首页查询商户支付全部流水
    getMerchantRecordsData() {
      getMerchantRecords(this.merchantId).then((res) => {
        let {
          allSales, // 营业总额
          todayPoints, // 今日积分总数
        } = res.data;
        this.allSales = allSales;
        // 总营业额
        this.totalList.forEach((item) => {
          Object.keys(res.data).forEach((key) => {
            if (item.key === key) item.value = res.data[key];
          });
        });
        // 今日业额
        this.totalProfit.forEach((item) => {
          Object.keys(res.data).forEach((key) => {
            if (item.key === key) {
              if (item.key == "todaySales") item.value = "¥ " + res.data[key];
              else item.value = res.data[key];
            }
          });
        });
        // 昨日数据
        this.yesterList.forEach((item) => {
          Object.keys(res.data).forEach((key) => {
            if (item.key === key) {
              if (item.key == "yesterdaySales")
                item.value = "¥ " + res.data[key];
              else item.value = res.data[key];
            }
          });
        });
        // 抵用卷和积分明细
        this.detailedList.forEach((item) => {
          item.list.forEach((e) => {
            Object.keys(res.data).forEach((key) => {
              if (e.key === key) e.value = res.data[key];
            });
          });
        });
        // 操作今日店铺总积分回显
        console.log("2222222222222222222", res.data, todayPoints);
        if (Number(todayPoints) > 0) {
          let str = todayPoints + "";
          let list = str.replace(".", "").split("");
          list.forEach((item, id) => {
            this.numList[this.numList.length - list.length + id] = Number(item);
          });
          // 没有数据就恢复默认值
        } else {
          this.numList = [0, 0, 0, 0, 0, 0, 0, 0, 0];
        }
      });
    },
    // 初始化商户信息
    getUserInfo() {
      this.loginStatus = Cache.get(LOGIN_STATUS) || this.$store.getters.isLogin;
      // console.log("999999999999999999", this.loginStatus);
      getUserInfoData().then((res) => {
        this.userInfo = res.data.sysUser;
        this.getTenantBySelfData();
      });
    },
    // 前往个人中心
    goToInfo() {
      uni.navigateTo({
        url: "/pages/myInfo/index",
      });
    },
    // 扫一下事件
    scanEvent() {
      // 未登录就跳登录页面
      this.power();
      uni.navigateTo({
        url: `/pages/order_payment/index`,
      });
    },
    // 前往登录
    power() {
      if (!this.loginStatus) {
        uni.navigateTo({
          url: `/pages/login/index`,
        });
        return;
      }
    },
    onTabChange(index) {
      // 可以在这里处理 Tab 切换的逻辑
    },
    // 下拉事件
    handlePickerChange(e) {
      this.selectedOption = this.options[e.detail.value];
      this.codeOptions.forEach((item) => {
        if (item.value == this.options[e.detail.value]) {
          this.selectedCode = item.code;
          this.merchantId = item.id;
          console.log("66666666666666666666", this.merchantId);
          this.getMerchantRecordsData();
        }
      });
    },
    /**
     * 用户点击右上角分享
     */
    // #ifdef MP
    onShareAppMessage: function () {
      let path = "";
      path = `/pages/index/index`;
      return {
        title: "测试",
        imageUrl: "",
        desc: "备注",
        path,
      };
    },
    // #endif
  },
};
</script>

<style lang="scss" scoped>
.page {
  padding: 120rpx 32rpx 0rpx 32rpx;
  .seachImg {
    width: 100rpx;
    height: 100rpx;
    border-radius: 12rpx;
  }
  .filter {
    margin-left: 21rpx;

    .code {
      margin-top: 6rpx;
      color: #91929b;
    }
  }
}
.downPoint {
  width: 26rpx;
  height: 14rpx;
  margin-left: 16rpx;
}
.businessTotal {
  margin-top: 42rpx;
  padding: 32rpx;
  background: #664fe9;
  .businessTitle {
    font-family: PingFang SC, PingFang SC;
  }
  .fraction {
    margin-top: 16rpx;
    font-weight: bold;
    font-size: 70rpx;
  }
  .unit {
    margin-left: 12rpx;
  }
  .details {
    font-size: 24rpx;
    margin-bottom: 12rpx;
  }
  .forwardArrow {
    margin-top: 6rpx;
    margin-left: 10rpx;
    width: 34rpx;
    height: 34rpx;
  }
}
.scanPart {
  height: 110rpx;
  box-shadow: 0rpx 2rpx 9rpx 2rpx rgba(0, 0, 0, 0.1);
  margin-top: 31rpx;
  .scanPartTitle {
    color: #664fe9;
  }
}
.todayStore {
  margin-top: 32rpx;
  padding: 20rpx 16rpx;
  .todayDate {
    font-size: 22rpx;
    color: #b9b9b9;
    margin-left: 12rpx;
  }
  .headStore {
    padding: 16rpx 27rpx 31rpx 27rpx;
  }
  .numPart {
    width: 56rpx;
    height: 82rpx;
    background: rgba(101, 79, 232, 0.16);
    border: 2rpx solid #664fe9;
    .numMark {
      font-size: 70rpx;
    }
  }
  .drop {
    width: 11rpx;
    height: 11rpx;
    background: #000000;
    border-radius: 50rpx;
    margin: 0rpx 10rpx 0rpx 16rpx;
  }
  .iconXinghao {
    width: 9rpx;
    height: 25rpx;
    color: #de4a2f;
    margin-right: 12rpx;
  }
  .introduce {
    font-size: 22rpx;
    color: #b9b9b9;
  }
}
.yesterday {
  height: 100rpx;
}
.detailedPart {
  padding: 28rpx 14rpx 19rpx 14rpx;
}
.tradePart {
  margin-top: 28rpx;
  border-radius: 14rpx;
}
.ml9 {
  margin-left: 9rpx;
}
.barCode {
  width: 400rpx;
  height: 400rpx;
}
.merchanTreceivePay {
  width: 30rpx;
  height: 30rpx;
}
.cardPart {
  width: 32%;
}
.header {
  margin-left: 19rpx;
}
</style>
